package com.example.accessibilityservice.server

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.content.res.Resources
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo

class MAccessibilityServer : AccessibilityService() {
    companion object {
        val TAG = "MAccessibilityServer"
    }

    val list: ArrayList<Rect> = ArrayList()
    var stop = false
    override fun onInterrupt() {

    }

    override fun onAccessibilityEvent(p0: AccessibilityEvent?) {
        when (p0?.eventType) {
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                stop = true
                list.clear()
//                Log.d(TAG, "onAccessibilityEvent: TYPE_WINDOW_STATE_CHANGED ${p0.packageName}")
                val source = p0.source
                println(source?.childCount)
                if (source != null) {
                    stop = false
                    getRects(source)
                    val intent = Intent(this, FloatingService::class.java)
                    intent.putParcelableArrayListExtra("rectList", list)
                    startService(intent)
                    Log.d(TAG, "onAccessibilityEvent: Done!!!")
                }
            }
        }

    }

    private fun getRects(source: AccessibilityNodeInfo) {
        if (stop) return
        for (i in 0 until source.childCount) {
            val nodeInfo = source.getChild(i)
            if (!nodeInfo.isVisibleToUser) continue
            if (nodeInfo != null) getRects(nodeInfo)
            val rect = Rect()
            val statusBarHeight = getStatusBarHeight()
            nodeInfo.getBoundsInScreen(rect)

            rect.top = rect.top - statusBarHeight
            rect.bottom = rect.bottom - statusBarHeight
            if (nodeInfo.text != null && !nodeInfo.text.isEmpty()) {
                list.add(rect)
                println("onAccessibilityEvent:(viewIdResourceName)$rect ${nodeInfo.text}")
            }
        }
    }

    fun getStatusBarHeight(): Int {
        val resources: Resources = Resources.getSystem()
        val resourceId: Int = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }
}